﻿/*
 * Creato da SharpDevelop.
 * Utente: Ciccio
 * Data: 28/09/2008
 * Ora: 13.09
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ACM.cmsarea08;
using ACM.cmsarea08.Controls;
using ACM.cmsarea08.Administration;


namespace ACM.cmsarea08.Administration.Core
{
	/// <summary>
	/// Description of AdminPage
	/// </summary>
	public class AdminPage : System.Web.UI.Page
	{
		public System.Resources.ResourceManager rm;
		public ACM.cmsarea08.Administration.Core.DBClass dclass = new cmsarea08.Administration.Core.DBClass();
		public ACM.cmsarea08.Function.TextClass textutility = new ACM.cmsarea08.Function.TextClass();
		public bool useCookie;
		
		public string CurrentLingua;

		override protected void OnInit(EventArgs e)
		{

			  if(Application["RM_ADM"]!=null)
    			rm = (System.Resources.ResourceManager) Application["RM_ADM"];
			  string clang = ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita;
				if(ACM.cmsarea08.Users.CurrentUser.Autorizzato)
					clang = ACM.cmsarea08.Users.CurrentUser.PrefLanguage;
							
				
			if(System.Threading.Thread.CurrentThread.CurrentCulture.Name!= clang) {
  	  		    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(clang);
 			    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(clang);
 		 	}			
			
			//aggiungere la chiamata a sessione per il check dei cookie.
			useCookie=true;
			InitializeComponent();
			base.OnInit(e);
			
		}		
		protected override void InitializeCulture()
		{
		  string clang = ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita;
			if(ACM.cmsarea08.Users.CurrentUser.Autorizzato)
				clang = ACM.cmsarea08.Users.CurrentUser.PrefLanguage;
			
			if(System.Threading.Thread.CurrentThread.CurrentCulture.Name!= clang) {
  	  		    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(clang);
 			    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(clang);
 		 	}
		    base.InitializeCulture();
		}		
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.CaricaPage);
		}		
		private void CaricaPage(object o , EventArgs e) {
			if(!this.Page.IsPostBack) {
				PrivatePathWay.privatePathWay.AddPagetoHistory(KindUrl.EditPage);
			}			
			if(!(ACM.cmsarea08.Users.CurrentUser.isRuolo("SysAdm") || 
			    ACM.cmsarea08.Users.CurrentUser.isRuolo("Admin") ||
			    ACM.cmsarea08.Users.CurrentUser.isRuolo("Content Manager")
			   )){
//				Response.Redirect("http://" + Request.ServerVariables["SERVER_NAME"]+"/administration/login.aspx");
			}
		}
		public string TablePrefix{
			get
            {
                return ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle;
            } 
		}		
		public void setViewState(object value, string key,bool storeinCookie) {
			if(useCookie && storeinCookie) {
				HttpCookie aCookie = new HttpCookie(key);
				aCookie.Value = value.ToString();
				aCookie.Expires = DateTime.Now.AddDays(1);
				HttpContext.Current.Response.Cookies.Add(aCookie);
				ViewState[key] = value;
			} else
				ViewState[key] = value;
		}
		public object getViewState(string key,bool readfromCookie) {
			if(useCookie && readfromCookie) {
				if( ViewState[key] != null)
					return ViewState[key];
				else if(HttpContext.Current.Request.Cookies[key] != null)
					return HttpContext.Current.Request.Cookies[key].Value;
				else
					return null;
			} else {
				if(ViewState[key] != null)
					return ViewState[key];
				else
					return null;
				
			}
		}		
		
		/* controllo pagina: */
		
		public string AddonsInstance {
			get {
				if(Request.Params["idi"]!=null)
					return Request.Params["idi"].ToString();
				else
					return "-1";
			}
		}
		public string AddonsComponent {
			get {
				if(Request.Params["idc"]!=null)
					return Request.Params["idc"].ToString();
				else
					return "-1";
			}
		}		
		public string getValidContentIDF() {
			//string:
			if(Request.Params["idf"]==null) return "-1";
			string idf = Request.Params["idf"].ToString();
			string vFound = "";
			string pType  = "";
			if(idf.ToLower().StartsWith("a")) {
				pType	="A";
				vFound 	=idf.Substring(1);
			} else if(idf.ToLower().StartsWith("c")) {
				pType	="C";
				vFound 	=idf.Substring(1);
			} else if(idf.ToLower().StartsWith("s")) {
				pType	="S";
				vFound 	=idf.Substring(1);
			} 
			
			if(pType=="S") { return vFound.Trim(); }
			if(pType=="C") {
				if(vFound.IndexOf('~')==-1) return "-1";
				else 
					return vFound.Substring(vFound.LastIndexOf('~')+1);
			}
			if(pType=="A") {
				if(vFound.IndexOf('~')==-1) return "-1";
				else 
					return vFound.Substring(vFound.LastIndexOf('~')+1);
			}
			return "-1";
		}
		public string[] getIDFRelatedAlternatives() {
			//string:
			if(Request.Params["idf"]==null) return new string[1] {"-1"};
			string idf = Request.Params["idf"].ToString();
			string vFound = "";
			string pType  = "";
			string[] alternative = new string[0];
			
			if(idf.ToLower().StartsWith("a")) {
				pType	="A";
				vFound 	=idf.Substring(1);
				alternative = new string[2];
			} else if(idf.ToLower().StartsWith("c")) {
				pType	="C";
				vFound 	=idf.Substring(1);
				alternative = new string[2];
			} else if(idf.ToLower().StartsWith("s")) {
				pType	="S";
				vFound 	=idf.Substring(1);
				alternative = new string[1];
			} 
			
			if(pType=="S") { 
				alternative[0] = "S" + vFound;
				return alternative;
			}
			if(pType=="C") {
				if(vFound.IndexOf('~')==-1) return new string[1] {"-1"};
				else {
					string[] vv = vFound.Split('~');
					if(vv.Length<2) return new string[1] {"-1"};
					alternative[0] = vv[0];
					alternative[1] = vv[0] + "~" + vv[1];
					return alternative;
				}
			}
			if(pType=="A") {
				if(vFound.IndexOf('~')==-1) return new string[1] {"-1"};
				else {
					string[] vv = vFound.Split('~');
					if(vv.Length<3) return new string[1] {"-1"};
					alternative[0] = vv[0];
					alternative[1] = vv[0] + "~" + vv[1];
					return alternative;
				}
			}
			return new string[1] {"-1"};
		}
		public DataSet ElencoGriglia {
			get {
				if(ViewState["ElencoGriglia"]==null)
					return null;
				else
					return (DataSet)ViewState["ElencoGriglia"];
			}
			set {
				ViewState["ElencoGriglia"]=value;
			}			
		}
		
		/* js utilities */
		public void PrintMessage(string message) {
			string js = "";
			js+="<script language=\"javascript\" type=\"text/javascript\"  defer=\"defer\">";
			js+="\n\r//<![CDATA[\n\r";
			js+="window.addEvent('domready', function() {";
			js+=" FlashMessage('"+message.Trim()+"'); ";
			js+="});";
			js+="\n\r//]]>\n\r";
			js+="</script>";
			this.Page.Controls.Add(new LiteralControl(js));				
		}
		public void ShowModal(string title, string url, string width, string height) {
			string js = "";
			js+="<script language=\"javascript\" type=\"text/javascript\"  defer=\"defer\">";
			js+="\n\r//<![CDATA[\n\r";
			js+="window.addEvent('domready', function() {";
			js+=" showModal('"+title.Trim()+"','"+url+"','"+width+"','"+height+"'); ";
			js+="});";
			js+="\n\r//]]>\n\r";
			js+="</script>";
			this.Page.Controls.Add(new LiteralControl(js));				
			
		}
		public string getDataBaseObject(object dato) {
			if(dato is byte[]) 
				return System.Text.Encoding.UTF8.GetString((byte[])dato);
			else
				return dato.ToString();
		}
		
		
		/* xml utility */
        public Control getXmlTransformation (System.Xml.XmlDocument xdoc, string xslpath, out string errors) {
        	errors = "";
        	if(xdoc==null ) {errors = "no XDOC"; return null;}
        	if(string.IsNullOrEmpty(xslpath) ) {errors = "no XPATH"; return null; }
        	if(this.Page== null ) 		  {errors = "no PAGE";  return null; }
        	
			Control controlli = null; 
        	try {
				System.Xml.Xsl.XslTransform XslTransform1 = 
					new System.Xml.Xsl.XslTransform();				
				//XPathDocument1 = new System.Xml.XPath.XPathDocument(mr);
				XslTransform1.Load(xslpath);
				System.IO.StringWriter StringWriter1 = new System.IO.StringWriter();
				XslTransform1.Transform(xdoc, null, StringWriter1, null);
				string aspPage = StringWriter1.ToString();
				aspPage = aspPage.Replace("xmlns:asp=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:ctl=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:tinymce=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:ptl=\"remove\"", "");
				controlli = this.Page.ParseControl(aspPage);
				
			} catch (Exception ex) {
				errors+=ex.ToString() ;
        		return null;
        	}
			return controlli ;        }
        public Control getXmlTransformation (System.Xml.XmlDocument xdoc, string xslpath) {
			string errors = "";
			return getXmlTransformation (xdoc,xslpath, out errors);
        }
        public Control getXmlTransformation (string xml, string xslpath) {
        	string errors = "";
        	return this.getXmlTransformation(xml,xslpath, out errors);
        }
        public Control getXmlTransformation (string xml, string xslpath, out string errors) {
        	errors = "";
        	if(string.IsNullOrEmpty(xml) ) {errors = "no XML"; return null; }
        	if(string.IsNullOrEmpty(xslpath) ) {errors = "no XSL"; return null;}
        	if(this.Page== null ) {errors = "no Page"; return null; }
        	
			Control controlli = null; 
        	try {
				
				System.IO.MemoryStream mr = 
					new System.IO.MemoryStream( System.Text.Encoding.UTF8.GetBytes(xml ));
				System.Xml.Xsl.XslTransform XslTransform1 = 
					new System.Xml.Xsl.XslTransform();
//				System.Xml.Xsl.XslCompiledTransform XslTransform1 = 
//					new System.Xml.Xsl.XslCompiledTransform();
				System.Xml.XmlDocument xdoc = 
					new System.Xml.XmlDocument();
				xdoc.Load(mr);
				//XPathDocument1 = new System.Xml.XPath.XPathDocument(mr);
				XslTransform1.Load(xslpath);
				
				System.IO.StringWriter StringWriter1 = new System.IO.StringWriter();
				XslTransform1.Transform(xdoc, null, StringWriter1, null);
				
				string aspPage = StringWriter1.ToString();
				aspPage = aspPage.Replace("xmlns:asp=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:ctl=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:tinymce=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:ptl=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"", "");
				aspPage = aspPage.Replace("xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"", "");
				aspPage = aspPage.Replace("xmlns:fn=\"http://www.w3.org/2005/xpath-functions\"", "");
				controlli = this.Page.ParseControl(aspPage);
				mr.Close();			
			} catch (Exception ex) {
				errors = ex.ToString();
        		return null;
        	}
			return controlli ;
        }
        public string getXmlTransformationString (string xml, string xslpath, out string errors) {
        	errors = "";
        	if(string.IsNullOrEmpty(xml) ) {errors = "no XML"; return null; }
        	if(string.IsNullOrEmpty(xslpath) ) {errors = "no XSL"; return null;}
        	if(this.Page== null ) {errors = "no Page"; return null; }
        	
			string textxml = ""; 
        	try {
				
				System.IO.MemoryStream mr = 
					new System.IO.MemoryStream( System.Text.Encoding.UTF8.GetBytes(xml ));
				System.Xml.Xsl.XslTransform XslTransform1 = 
					new System.Xml.Xsl.XslTransform();
//				System.Xml.Xsl.XslCompiledTransform XslTransform1 = 
//					new System.Xml.Xsl.XslCompiledTransform();
				System.Xml.XmlDocument xdoc = 
					new System.Xml.XmlDocument();
				xdoc.Load(mr);
				//XPathDocument1 = new System.Xml.XPath.XPathDocument(mr);
				XslTransform1.Load(xslpath);
				
				System.IO.StringWriter StringWriter1 = new System.IO.StringWriter();
				XslTransform1.Transform(xdoc, null, StringWriter1, null);
				
				string aspPage = StringWriter1.ToString();
				aspPage = aspPage.Replace("xmlns:asp=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:ctl=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:tinymce=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:ptl=\"remove\"", "");
				aspPage = aspPage.Replace("xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"", "");
				aspPage = aspPage.Replace("xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"", "");
				aspPage = aspPage.Replace("xmlns:fn=\"http://www.w3.org/2005/xpath-functions\"", "");
				textxml = aspPage;
				mr.Close();			
			} catch (Exception ex) {
				errors = ex.ToString();
        		return "";
        	}
			return textxml ;
        }
		
		
		/* url utility */
		public string getValidURL(string lang, string sourceid, string destinationid, string type){
			
			if(lang!=string.Empty && sourceid!=string.Empty && destinationid!=string.Empty && type!=string.Empty){
				
				if(lang.Length!=0 && sourceid.Length!=0 && destinationid.Length!=0 && type.Length!=0){
					return HttpUtility.HtmlEncode(ACM.cmsarea08.Core.UrlManager.GetUrl(lang,sourceid,destinationid,type));
				}
				else
					return "/default.aspx";
			}
			else
				return "/default.aspx";
				
		}
		public string getValidURL(string lang, string sourceid, string destinationid, string type, bool W3CCompliance){
			string url = "/default.aspx";
			if(lang!=string.Empty && sourceid!=string.Empty && destinationid!=string.Empty && type!=string.Empty){
				
				if(lang.Length!=0 && sourceid.Length!=0 && destinationid.Length!=0 && type.Length!=0){
					url = ACM.cmsarea08.Core.UrlManager.GetUrl(lang,sourceid,destinationid,type);
					if(W3CCompliance)
						url = HttpUtility.HtmlEncode(url);
				}
			}
			return url;
						
		}
		public string getContentURL(string lang, string sourceid, ACM.cmsarea08.Core.UrlManager.ContentUrlTypes contenturltype, params string[] ids) {
			return HttpUtility.HtmlEncode(ACM.cmsarea08.Core.UrlManager.GetContentUrl(lang,sourceid,contenturltype, ids));
		
        }

		
		/* text class */
		public ACM.cmsarea08.Function.TextClass textClass {
			get {
				return ACM.cmsarea08.Function.TextClass.textclass;
			}
		}
	}
}
